//
//  AticHeadView.m
//  diaoyuren
//
//  Created by 单安成 on 15/12/23.
//  Copyright © 2015年 game. All rights reserved.
//

#import "AticHeadView.h"
#import "AppDelegate.h"

#define CollectYes  @"YES"
#define colletNo  @"NO"

@interface AticHeadView ()
@property (nonatomic,copy) NSString *filePath;
@property (nonatomic,strong) NSMutableArray *colleAry;
@property (nonatomic,strong) AppDelegate *app;
@end
@implementation AticHeadView

-(NSMutableArray *)colleAry{
    if (!_colleAry) {
        _colleAry = [NSMutableArray array];
    }
    return _colleAry;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        self.app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        
        _BackBnt=[UIButton buttonWithType:UIButtonTypeCustom];
        _BackBnt.frame = CGRectMake(0, 0, 120, 64);
        _BackBnt.imageEdgeInsets = UIEdgeInsetsMake(20, 15, 0, 0);
        [_BackBnt setImage:[UIImage imageNamed:@"btn-return"] forState:UIControlStateNormal];
        [_BackBnt setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        [_BackBnt setTitle:@"ButtonButton" forState:UIControlStateNormal];
        [self addSubview:_BackBnt];
        
        _titile = [[MBLabelWithFontAdapter alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-100)/2, 20, 100, 44)];
        _titile.textAlignment = NSTextAlignmentCenter;
        _titile.font = [UIFont systemFontOfSize:18];
        [self addSubview:_titile];
        
        //分享
        _shareBnt=[UIButton buttonWithType:UIButtonTypeCustom];
        _shareBnt.frame = CGRectMake(SCREEN_WIDTH-40-5, 20, 40, 44);
        [_shareBnt setImage:[UIImage imageNamed:@"btn-share"] forState:UIControlStateNormal];
        [self addSubview:_shareBnt];
        
        //收藏
        _collectBnt=[UIButton buttonWithType:UIButtonTypeCustom];
        _collectBnt.frame = CGRectMake(SCREEN_WIDTH-40-40-5 , 20, 40, 44);
        [_collectBnt setImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
        [_collectBnt addTarget:self action:@selector(Collect:) forControlEvents:UIControlEventTouchUpInside];
        
        [_collectBnt setImage:[UIImage imageNamed:@"btn-collectioned"] forState:UIControlStateSelected];
        [self addSubview:_collectBnt];

        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, H(self)-1, SCREEN_WIDTH, 1)];
        view.backgroundColor = RGBA(229, 229, 229, 1);
        [self addSubview:view];
    }

        return self;
}

-(void)setIsLogin:(NSString *)isLogin{
    _isLogin = isLogin;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/collect",NSHomeDirectory()];;

    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    
    self.filePath  = [NSString stringWithFormat:@"%@/collect.plist",path];
    
    if (![fileManager fileExistsAtPath:self.filePath]) {
     
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic writeToFile:self.filePath atomically:YES];
    }
    
    if ([_isLogin isEqualToString:@"YES"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 2.0), dispatch_get_main_queue(), ^{
            self.userModel = self.app.userModel;
        });
    }
}

-(void)setUserModel:(UserDataModel *)userModel{
    _userModel = userModel;
    NSString *url= [NSString stringWithFormat:@"http://school.diaoyur.cn/article/user-collection?uid=%@",self.app.userModel.uid];
    
    [[Manager sharedManager]RequestWhithURL:url AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        if ([responseObject[@"status"] isEqualToString:@"SUCCESS"]) {
            [ self.colleAry addObjectsFromArray:responseObject[@"data"][@"collection"]];
            
            NSMutableDictionary *ddd = [NSMutableDictionary dictionaryWithContentsOfFile:self.filePath];
            for (NSDictionary *dic in self.colleAry) {
                if ([ddd[self.AtcID] isEqualToString:CollectYes]||[dic[@"aid"] isEqualToString:self.AtcID]) {
                    _collectBnt.selected = YES;
                }
            }
        }
    }];
}

#pragma mark---收藏操作
-(void)Collect:(UIButton *)sender{
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
      
        if (!sender.selected) {
            [self POSTCollectWhithAction:@"add"];
        }else{
            [self POSTCollectWhithAction:@"cancel"];
        }
    }else{
        [self.deleget collectMaseege:NO Message:@"您还未登录，不能收藏"];
    }
    
}

#pragma mark---收藏操作请求
-(void)POSTCollectWhithAction:(NSString *)action{

    if (self.userModel.uid) {
        NSDictionary *dic = @{@"uid":self.userModel.uid,@"article_id":self.AtcID};
        NSString *url = [NSString stringWithFormat:@"http://school.diaoyur.cn/article/%@-collection",action];
        [[Manager sharedManager]ResponseWhithURL:url AndParameter:dic AndCompletionType:^(id responseObject, DIEError *error) {
            [self.deleget collectMaseege:YES Message:responseObject[@"message"]];
    
            if ([responseObject[@"message"] isEqualToString:@"添加成功"]) {
                
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:self.filePath];
                [dic setValue:CollectYes forKey:self.AtcID];
                [dic writeToFile:self.filePath atomically:YES];
                _collectBnt.selected = YES;
            }else if ([responseObject[@"message"] isEqualToString:@"取消成功"]){
                _collectBnt.selected = NO;
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:self.filePath];
                [dic setValue:colletNo forKey:self.AtcID];
                [dic writeToFile:self.filePath atomically:YES];
            }
        }];
    }
}
@end